<template>
	<view :class="modalName ? 'prevents' : ''">
		<j-load v-if="loading"></j-load>
		<view v-else class="padding-tb padding-left">
			<!-- 请求超时 -->
			<j-timeOut v-if="timeOut"></j-timeOut>
			<view v-else>
				<view v-if="Me.fail" class="margin-right margin-bottom">
					<!-- 未开通  -->
					<unBuy v-if="!Me.isShow" :urlParams="urlParams"></unBuy>
					<!-- 已开通 -->
					<hasOpen v-else :message="Me.message" :urlParams="urlParams" @renewalClick="renewalClick"></hasOpen>
				</view>
				<!-- 套餐列表 -->
				<good-list :list="goods" :urlParams="urlParams" @click="goodsClick"></good-list>
				<!-- 点击套餐后的底部价格 -->
				<bottom-price v-show="bottomMessage.isShow" :buyCheck="bottomMessage.buyCheck" :message="bottomMessage.paid" @purchaseKnown="purchaseKnown" @buyClick="buyClick" @checkClick="(val)=>bottomMessage.buyCheck=val"></bottom-price>
			</view>
		</view>
	
		<!-- 购买须知 弹框  PurchaseNotes-->
		<purchase-notes ref="purchases" :modalName="modalName" :notes="purchaseNotes" @IKnownClick="handleIKnown" @hideModal="hideModal"></purchase-notes>
		<!-- 套餐购买详情弹框 bottomModal-->
		<detail :modalName="modalName" :urlParams="urlParams" :paid="buyMessage" :payType="typeList" :specifications="specifications" :country="country" @goodsClick="goodsClick" @payClick="payClick"  @selectBuyNum="goodsClick" @selectCoupon="selectCoupon" @selectIntegral="selectIntegral"></detail>
		<!-- 有未完成订单 弹框 payFail-->
		<pay-fail :modalName="modalName" @hideModal="hideModal"></pay-fail>
		<!-- 支付加载 模态框 -->
		<j-load-modal v-if="loadModal"></j-load-modal>
		<!-- 失败弹框 -->
		<error-modal :modalName="modalName" :errCode="errCode" :message="errMessage" @changeModalName="hideModal"  @clearCacheClick="clearCacheClick"></error-modal>
		<!-- 优惠券 模态框 -->
		<coupon-modal ref="couponModalRef" :modalName="couponModalName" :list="currentaCoupons" @hideModal="hideModal" @submit="couponSubmit"></coupon-modal>
		<!-- 抵扣券 -->
		<integral-modal ref="intergralRef" :modalName="IntegralModalName" :message="buyMessage" @hideModal="hideModal" @submit="integralSubmit"></integral-modal>
	</view>
</template>

<script>
import errorModal from "../components/modal/error"
import couponModal from "../components/modal/coupon"
import integralModal from "../components/modal/integral"
import unBuy from "./unBuy/unBuy"//未开通
import goodList from './goodList/goodList'// 套餐列表
import purchaseNotes from './purchaseNotes/purchaseNotes'//购买须知 弹框
import bottomPrice from './bottomPrice/bottomPrice'//点击套餐后的底部价格
import detail from './detail/detail'//套餐购买详情 弹框
import payFail from './payFail/payFail'//支付失败 弹框
import hasOpen from './hasOpen/hasOpen'//已开通
import { handleMax } from '@/utils/index.js'
import { getGoods, getBuy,getPlaceOrder ,getPurchaseNotes } from '@/API/api.js'
import orderStatusOrPayType from '@/jvss/pageCloud/utils/pay.js'
import Purchased from '@/jvss/pageCloud/utils/Me.js'
import logins from '@/utils/loginApi.js'
import wxMessage from '@/utils/wx.js'
const {wxPay} = wxMessage();
const { handlePayType } = orderStatusOrPayType();//订单状态查询或支付类型
const {handleLogin,httpReturn} = logins();
const { handleMe } = Purchased();//已购信息
export default {
	components: {
		errorModal,
		couponModal,
		integralModal,  
		unBuy,
		goodList,
	    purchaseNotes,
	    bottomPrice,
	    detail,
	    payFail,
	    hasOpen
	},
	data(){
		return{
			// url参数
			urlParams: {
				deviceId: '',
				channel: '',
				classifyId: ''
			},
			title: '', //标题
			goods: [], //套餐列表
			loading: true, //页面进入的加载
			timeOut: false, //接口请求是否超时
			Me: {
				isShow: false, //是否已购买
				fail:false,//是否加载成功
				message: []
			},
			typeList:[],//通过后台获取支付列表
			modalName:'',//模态框弹出字段
			bottomMessage:{
				paid:{},
				buyCheck:false,
				isShow:false
			},
			buyMessage:{},//购买计算信息
			loadModal:false,//支付加载模态框
			errCode:'',//失败code值
			errMessage:{},//失败接口返回的data信息
			specifications:[],//规格
			goodClickPaid:{},//外部套餐点击获取的数据
			couponModalName:'',//优惠券模态框name
			IntegralModalName:'',//积分抵扣模态框name
			currentaCoupons:[],//当前选择的套餐优惠券信息
			country:'',
			usingIntegral:true,
			devicePid:'',
			purchaseNotes:'', //购买须知内容
		}
	},
	onLoad(e) {
	  	const {sn,channel,classifyId,devicePid} = e;
		this.title = this.groupsTitle(classifyId);
        uni.setNavigationBarTitle({title: this.title})
		// url上的参数
		this.urlParams = {
			deviceId: sn,
			channel:channel==='undefined' ? '': channel,
			classifyId
		}
		this.devicePid = devicePid==='undefined' || !devicePid ? '':devicePid
		console.log('跳转===',e);
		this.getNotice();
	},
	onShow() {
		this.modalName = '';
		this.bottomMessage.isShow = false;
		this.bottomMessage.buyCheck=false
		handleLogin(() => {
			// 已购买信息
			handleMe(this.urlParams,(message)=>{
				this.Me = message;
			})
			this.handleGoods(); // 套餐列表
			//支付类型
			const {deviceId,classifyId} = this.urlParams;
			handlePayType({deviceId,classifyId},(data)=>{
				const {country,payTypes} = data;
				this.typeList = payTypes;
				this.country = country;
			})
		})
	},
	methods: {
		//购买须知
		getNotice(){
			let param ={classifyId:this.urlParams.classifyId,language:'zh_CN',deviceId:this.urlParams.deviceId}
			getPurchaseNotes(param).then((res)=>{
				console.log('获取购买须知',res);
				this.purchaseNotes = res.data.purchaseNotes
			})
		},
		groupsTitle(classfyId){
			switch(classfyId){
				case 'xmc.css':
					return this.$t('JLink.groups.xmcCss')
				case 'xmc.voes':
					return this.$t('JLink.groups.xmcVoes')
				case 'pms.voes':
					return this.$t('JLink.groups.pmsVoes')
				case 'pms.sms':
					return this.$t('JLink.groups.pmsSms')
				case 'net.cellular':
					return this.$t('JLink.groups.netCellular')
			}
		},
		// 换4G卡清缓存
		clearCacheClick (){
			this.modalName = '';
			handleLogin(()=>{
				 this.handleGoods(true)
			})
		},
		// [获取]套餐列表
		handleGoods (clearCache = false){
			this.loading = true; //加载中
			let params = Object.assign({},this.urlParams,{clearCache,devicePid:this.devicePid,language:'zh_CN',newSpecifications:true})
			console.log('参数===',params);
			getGoods(params).then(res => {
				this.loading = false; //停止加载
				this.timeOut = false;
				httpReturn(res, (data) => {
				  this.goods = data || []; //数据
				  console.log('套餐列表===',this.goods);
          this.goods.map((t) => {
					t.specifications = (t.specifications || []).filter((item) => {
            return !item.automaticPayment
          });//规格
					t.specifications.forEach((z) => {
					  z.check = false;
					  z.name = t.name;
					});
				  });
          // this.goods.filter((item) => {
          //
          // })
				}, (code,data) => {
				  this.modalName = 'errorMessage';//接口返回错误弹框
				  this.errCode = code;
				  this.errMessage = data;//接口返回的错误data
				})
			}).catch(() => {
				this.loading = false; //停止加载
				this.timeOut = true; //失败(做超时提示)
			})
		},
		// 套餐点击事件
		goodsClick(paid,item){
		  if(item){
			this.specifications = item.specifications;//规格
			this.goodClickPaid = paid;//套餐点击获取的数据
		  }
		  this.bottomMessage.paid = paid;
		  this.bottomMessage.isShow =  true;
		  this.usingIntegral = true;
		  if(!this.bottomMessage.buyCheck){
			this.purchaseKnown();
		  }
		  this.handlePrice(paid)
		  if(item=='close'){
			this.hideModal()
		  }
		},
		// 购买价格计算
		handlePrice(paid,couponId_){
			const { id, buyNum } = paid;
			const {deviceId,channel} = this.urlParams;
			let buyParamsClass={
				goodsId:id,
				deviceId:deviceId,
				buyNum: buyNum,
				channel :channel,
				couponId :couponId_,
				usingIntegral:this.usingIntegral,
			}
			this.buyMessage = paid
			this.buyMessage.payAmount = '--.--';
			getBuy(buyParamsClass).then((res) => {
				httpReturn(res, (data) => {
				  const {coupons,useCouponId,useCouponAmount,currencyUnit} = data;
				  this.buyMessage = Object.assign({}, paid, data || {},{usingIntegral:this.usingIntegral});
				  this.currentaCoupons = coupons;//当前选择的套餐优惠券列表
				  this.buyMessage.selectCouponVal = `-${currencyUnit}${useCouponAmount}`//选择的优惠券价格
				  this.buyMessage.selectCouponId = useCouponId;//选择的优惠券id
				  this.$refs.couponModalRef.couponId = useCouponId;
				  this.buyMessage.MaxVal = handleMax(coupons,'couponAmount')//获取优惠券最大值
			    }, (code) => {
				  this.modalName = 'errorMessage';//接口返回错误弹框
				  this.errCode = code;
			    })
			}).catch(()=>{});
		},
		// 购买须知
		purchaseKnown(){
		    this.modalName = 'PurchaseNotes';//弹出购买须知
		   	this.$refs.purchases.handleIntervalTime();
		},
		// 我知道
		handleIKnown(){
		  this.modalName = 'bottomModal';//弹出购买详情
		  this.bottomMessage.buyCheck = true;
		},
		// 底部立即购买点击
		buyClick(){
			let code;
			let eventName;
			switch (this.urlParams.classifyId){
				case 'xmc.css':
					code='603060'
					eventName='xmcCss_goods_buyNow'
					break;
				case 'xmc.voes':
					code='603063'
					eventName='xmcVoes_goods_buyNow'
					break;
				case 'pms.voes':
					code='603066'
					eventName='pmsVoes_goods_buyNow'
					break;
				case 'pms.sms':
					code='603069'
					eventName='pmsSms_goods_buyNow'
					break;
				case 'net.cellular':
					code='603072'
					eventName='netCellular_goods_buyNow'
					break;
			}
			const pointData={ code,eventName }
			this.$postPointData(pointData)
		  if(this.bottomMessage.buyCheck){
			this.modalName='bottomModal';
		  }else{
			this.purchaseKnown()
		  }
		},
		// 续费
		renewalClick({goodsId}){
		    this.bottomMessage.isShow =  false
		    let isExist = false;
		    if(this.goods.length){
				this.goods.forEach(z=>{
				  z.specifications.forEach((j) => {
					j.check = false;
					if(this.urlParams.classifyId&&this.urlParams.classifyId==='net.cellular'){
					  if(j.id==goodsId){
						j.check = true;
						 this.goodsClick(j,z)
						isExist = true;
					  }
					}
				  });
				  if(this.urlParams.classifyId&&this.urlParams.classifyId!='net.cellular'){
					if(z.id==goodsId){
					  if(z.specifications&&z.specifications.length){
						let paid = z.specifications[0];
						paid.check = true;
						 this.goodsClick(paid,z)
						isExist = true;
					  }
					}
				  }
				})
				// 没有此套餐id,默认选择第一个套餐分类数组的第一个
				if(!isExist){
				  let paid =this.goods[0].specifications[0];
				  paid.check = true;
				  this.goodsClick(paid,this.goods[0])
				}
            }
			// 	续费埋点处理
			let code;
			let eventName;
			switch (this.urlParams.classifyId){
				case 'xmc.css':
					code='603059'
					eventName='xmcCss_goods_renewal'
					break;
				case 'xmc.voes':
					code='603062'
					eventName='xmcVoes_goods_renewal'
					break;
				case 'pms.voes':
					code='603065'
					eventName='pmsVoes_goods_renewal'
					break;
				case 'pms.sms':
					code='603068'
					eventName='pmsSms_goods_renewal'
					break;
				case 'net.cellular':
					code='603071'
					eventName='netCellular_goods_renewal'
					break;
			}
			const pointData={ code,eventName }
			this.$postPointData(pointData)
        },
		// 优惠券模态框显示
		selectCoupon (){
		  this.couponModalName = 'couponModal';
		  this.$refs.couponModalRef.couponId = this.buyMessage.selectCouponId;
		},
		// 优惠券选择的字段
		couponSubmit(message){
		  this.couponModalName=''
		  const {currencyUnit,couponAmount,couponId} = message;
		  this.buyMessage.selectCouponVal = `-${currencyUnit}${couponAmount}`;//选择的优惠券价格
		  this.buyMessage.selectCouponId = couponId;//选择的优惠券id
		  this.handlePrice(this.buyMessage,couponId)
		},
		// 抵扣券模态框显示
		selectIntegral(){
		  this.IntegralModalName = 'integralModal';
		},
		// 积分
		integralSubmit(val){
		  this.IntegralModalName=''
		  this.buyMessage.usingIntegral = val;
		  this.usingIntegral = val;
		  console.log(this.buyMessage,999,val)
		  this.handlePrice(this.buyMessage)
		},
		// 下订单
		payClick(payType,paid,urlParams){
			this.loadModal = true;
			const {id,buyNum,selectCouponId,usingIntegral,currencyUnit,payAmount} = paid;
			const {deviceId,channel} = urlParams;
			let params={
				goodsId:id,
				deviceId:deviceId,
				buyNum: buyNum,
				payType: payType,
				channel :channel==='undefined' ? undefined : channel,
				couponId :selectCouponId ? selectCouponId : -1,
				usingIntegral : usingIntegral
			}
			getPlaceOrder(params).then(res=>{
				httpReturn(res,(data=>{
				  const {orderId} = data;
				  this.loadModal = false;
				  //小程序支付
				  wxPay(orderId)
				}),(code=>{
				  this.loadModal = false;
				  //有未完成订单
				  if(code===4010){
					this.modalName = 'payFail';
				  }else{
					this.modalName = 'errorMessage';//接口返回错误弹框
					this.errCode = code;
				  }
				}))
				}).catch(()=>{
				  this.loadModal = false;
			})
		},
		hideModal(){
			this.modalName=''
		}
	}
}
</script>
<style lang="less" scoped>
	@import '@/common/style/main.css';
</style>
